//
//  WBMainTableViewController.swift
//  Swift_sina
//
//  Created by TFB_WGP on 2017/8/16.
//  Copyright © 2017年 TFB_WGP. All rights reserved.
//

import UIKit
import SVProgressHUD

///通过网络现在一个json文件来改变App界面的逻辑的介绍

//主控制器
class WBMainTableViewController: UITabBarController {

//  定时器
    fileprivate var timer: Timer?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setupChildController()
        setupComposeBtn()
        setupTimer()
        
//        设置代理
        delegate = self
        
//        注册通知
        NotificationCenter.default.addObserver(self, selector: #selector(userLogin(n:)), name: NSNotification.Name(rawValue: WBUserShouldLoginNotifiction), object: nil)
    }
    
    deinit {
//        定时器记得销毁
        timer?.invalidate()
//        主线通知
        NotificationCenter.default.removeObserver(self)
    }
    
    //设置设备支持方向之后,当前控制器及子控制器都会支持这个方向
    //如果播放视频通常是modal展示
    override var supportedInterfaceOrientations: UIInterfaceOrientationMask{
        return .portrait
    }
    
    @objc fileprivate func userLogin(n: Notification){
         print("登录")
        
        var when = DispatchTime.now()
        
        if n.object != nil {
            SVProgressHUD.setDefaultStyle(.light)
            SVProgressHUD.showInfo(withStatus: "用户登录超时,请重新登录")
            when = when+2
        }
        
        DispatchQueue.main.asyncAfter(deadline: when) {
            let vc = UINavigationController(rootViewController: WBLoginViewController())
            self.present(vc, animated: true, completion: nil)
        }
    }
    
    //MARK: - 监听方法
    /// filerprivate保证方法私有,@objc保证方法在运行时能够被OC的消息机制调用
    @objc fileprivate func composeStatus() -> Void {
        print("发微博")
    }
    
    //MARK: - 私有控件
    fileprivate lazy var composeBtn: UIButton = {
        
        let btn = UIButton()
        btn.setBackgroundImage(UIImage(named: "tabbar_compose_button"), for: UIControlState.normal)
        btn.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), for: UIControlState.highlighted)
        btn.setImage(UIImage(named: "tabbar_compose_icon_add"), for: .normal)
        btn.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), for: .highlighted)
        btn.addTarget(self, action: #selector(composeStatus), for: .touchDown)
        return btn
    }()
}

extension WBMainTableViewController: UITabBarControllerDelegate{
    //检测tabbarItem的点击
    /// 将要点击tabnarItem
    ///
    /// - Parameters:
    ///   - tabBarController
    ///   - viewController:
    /// - Returns: 是否切换到目标控制器
    func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
        
        let index = viewControllers?.index(of: viewController)
        if selectedIndex == 0 && index == selectedIndex {
            //说明是首页,让表格滚动到顶部
            let nav = childViewControllers[0] as! UINavigationController
            let vc = nav.childViewControllers[0] as! WBHomeViewController
            
            vc.tableView?.setContentOffset(CGPoint(x:0, y:-64), animated: true)
            //刷新数据
            DispatchQueue.main.asyncAfter(deadline: DispatchTime.now()+1, execute: {
                vc.loadData()
            })
        }
//        判断目标控制器是否是UIVIewController
//        防止切换到容错点控制器
        return !viewController.isMember(of: UIViewController.self)
    }
}

//MARK: - 时钟相关方法
extension WBMainTableViewController{
    
//    定义时钟
    fileprivate func setupTimer(){
        
        timer = Timer.scheduledTimer(timeInterval: 8.0, target: self, selector: #selector(update), userInfo: nil, repeats: true)
    }
    
    @objc private func update(){
        
        if !NetworkRequest.sharedInstance.isLogin {
            return
        }
        
        NetworkRequest.sharedInstance.unreadCount { (count) in
            WPPrint(items: "检测到\(count)条数据")
            //设置tabbar的badgeValue
            self.tabBar.items![0].badgeValue = count>0 ? "\(count)" : nil
            
            //设置App的badgeNumber,iOS8.0之后需要用户授权
            UIApplication.shared.applicationIconBadgeNumber = count
        }
    }
}

//extension相当于OC中的分类,在swift中还可以用来切分代码块
//可以吧相近功能的函数,放到一个extension中
//注意:和OC的分类一样,extension终不能定义属性
// MARK: - 设置界面
extension WBMainTableViewController{
    
    fileprivate func setupComposeBtn(){
        tabBar.addSubview(composeBtn)
        
        //设置按钮的位置
        let count = CGFloat(childViewControllers.count)
        let w = tabBar.bounds.width / count  -  1
//        正数向内缩进,负数向外
//        盖住容错点,防止穿帮
        composeBtn.frame = tabBar.bounds.insetBy(dx: 2*w, dy: 0)
    }
    
    //设置所有的子控制器
    fileprivate func setupChildController(){
        
        var data = NSData(contentsOfFile: jsonPath)
        if data == nil {
            //从bundle加载
            let path = Bundle.main.path(forResource: "Main.json", ofType: nil)
            data = NSData(contentsOfFile: path!)
        }
        
        let array = try! JSONSerialization.jsonObject(with: data! as Data, options: []) as? [[String:Any]]
        
//        let array: [[String:Any]] = [
//        ["clsName":"WBHomeViewController","title":"首页","imageName":"home","visitorInfo":["imageName":"","message":"你还没有关注一些人。关注自己感兴趣的人，可在\n这里看到他们发布的内容"]],
//        ["clsName":"WBMessageViewController","title":"消息","imageName":"discover","visitorInfo":["imageName":"visitordiscover_image_message","message":"登陆后，别人评论你的微博，给你\n发消息，都会在这里受到通知"]],
//        ["clsName":"UIViewController"],
//        ["clsName":"WBDiscoverViewController","title":"发现","imageName":"message_center","visitorInfo":["imageName":"","message":"发现"]],
//    ["clsName":"WBProfileViewController","title":"我","imageName":"profile","visitorInfo":["imageName":"visitordiscover_image_profile","message":"登陆后，你的微博、相册、个人资料\n会显示在这里，展示给别人"]],
//        ]
        
        //保存至plist文件存起来
//        (array as NSArray).write(to: <#T##URL#>, atomically: <#T##Bool#>)
        //数组到json->序列化
//        let data = try! JSONSerialization.data(withJSONObject: array, options: [.prettyPrinted])
//        print((data as NSData).write(toFile: "/Users/tfb_wgp/Desktop/data666.json", atomically: true))
        
        var  arrM = [UIViewController]()
        for dict in array! {
            arrM.append(controller(dict: dict))
        }
        
        viewControllers  = arrM
    }
    
    //使用一个字典创建一个字控制器
    private func controller(dict: [String:Any])->UIViewController{
        
        //取得子店内容
        guard let clsName = dict["clsName"] as? String,
            let title = dict["title"] as? String,
            let imageNmae = dict["imageName"] as? String,
        let cls = NSClassFromString(Bundle.main.namespace + "." + clsName) as? WBBaseViewController.Type,
        let visitorDict = dict["visitorInfo"] as? [String:String] else {
            return UIViewController()
        }
        
//        创建视图控制器
        let vc = cls.init()
        vc.visitorInfo = visitorDict
        vc.title = title
        let nav = WBNavigationViewController(rootViewController: vc)
        
        //设置图像
        vc.tabBarItem.image = UIImage(named: "tabbar_"+imageNmae)
        vc.tabBarItem.selectedImage = UIImage(named: "tabbar_" + imageNmae + "_selected")?.withRenderingMode(.alwaysOriginal)
        
        vc.tabBarItem.setTitleTextAttributes([NSForegroundColorAttributeName:UIColor.orange], for: .selected)
//        系统默认是12号字体
        vc.tabBarItem.setTitleTextAttributes([NSFontAttributeName:UIFont.systemFont(ofSize: 13)], for: UIControlState(rawValue: 0))
        return nav
    }
}
